<template>
  <div style="width: 100%" class="image">
   <el-dialog visible :close-on-click-modal="false" title="上传图片" width="800px" @close="close">
      <div :style="delStyle">
        <i v-if="baseImgFileUrl" class="el-icon-error delete" @click="delImg"></i>
      </div>
      <el-image v-if="baseImgFileUrl" :style="imgStyle" :src="baseImgFileUrl" :fit="fit">
      </el-image>
      <div v-if="!baseImgFileUrl">
        <el-upload class="avatar-uploader" accept="image/*" v-loading="loading" action="" show-file-list
          :before-upload="beforeAvatarUpload" :http-request="uploadFile" :disabled="disabled">
          <i class="el-icon-plus avatar-uploader-icon" :style="iconStyle"></i>
        </el-upload>
      </div>
     <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios"
import { localStore } from '@/utils/sessionStore'
import { loadRoute3Path } from '@/utils/loadRemote'
export default {
  props: {
    value: {},
    fit: {
      type: String,
      default: "contain",
    },
    imgWidth: {
      type: [Number, String],
      default: 200,
    },
    imgHeight: {
      type: [Number, String],
      default: 200,
    },
    fileSize: {
      type: [Number, String],
      default: 5,
    },
  },
  data() {
    return {
      imgFileUrl: "",
      loading: false,
    }
  },
  watch: {
  },
  computed: {
    imgStyle() {
      return {
        width: this.imgWidth + "px",
        height: this.imgHeight + "px",
        "background-color": "#F5F5F5",
      }
    },
    iconStyle() {
      return {
        width: this.imgWidth + "px",
        height: this.imgHeight + "px",
        "line-height": this.imgHeight + "px",
      }
    },
    delStyle() {
      return {
        width: this.imgWidth + "px",
        height: "20px",
        "text-align": "right",
        "margin-bottom": "-5px",
      }
    },
    baseImgFileUrl() {
      if (this.imgFileUrl) {
        const uniqueId = localStorage.getItem("uniqueId").replace(/\"/g, "")
        return `${this.imgFileUrl}?Authorization=${uniqueId}`
      } else {
        return ""
      }
    },
    prefix(){
      const globalConfig = localStore.get('globalConfig') // 读取全局配置
      if (globalConfig  && globalConfig.apiPrefix.path){
        const path = globalConfig.apiPrefix.path
        return path.endsWith('/') ? path.slice(0, -1) : path
      } else {
        return ''
      }
    },
    pathname() {
      return loadRoute3Path('')
    }
  },
  mounted() {},
  methods: {
    uploadFile(obj) {
      this.toUploadFile(obj)
    },
    beforeAvatarUpload(file) {
      const reg = /\.(git|jpg|jpeg|png|GIF|JPG|PNG)$/
      const isJPG = reg.test(file.name)
      const isLt2M = file.size / 1024 / 1024 < this.fileSize
      if (!isJPG) {
        this.$message.error("上传图片只能是 git|jpg|jpeg|png|GIF|JPG|PNG 格式!")
      }
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过 ${this.fileSize}MB!`)
      }
      return isJPG && isLt2M
    },
    async toUploadFile(obj) {
      this.loading = true
      const uniqueId = localStorage.getItem("uniqueId").replace(/\"/g, "")
      const newHeaders = {
        Authorization: uniqueId,
        "Content-Type":
          "multipart/form-data;boundary=<calculated when request is sent>",
      }
      let params = new FormData()
      params.append("attachments", obj.file)
      const action = "api/lowcode/models/attachments/actions/upload"
      const url = window.location.origin + `${this.pathname}${this.prefix}/` + action
      axios({
        method: "post",
        url: url,
        headers: newHeaders,
        data: params,
      })
        .then((res) => {
          if (res.status == 200) {
            this.loading = false
            const fileId = res.data[0].fileId
            const pre = `${this.prefix}/`
            this.imgFileUrl = `${this.pathname}${pre}api/lowcode/models/attachments/${fileId}/actions/download`
            this.$emit("input", this.baseImgFileUrl)
          }
        })
        .catch((err) => {
          this.loading = false
          console.error("上传图片出错", err)
        })
    },
    delImg() {
      this.imgFileUrl = null
    },
    close() {
      this.$emit('close')
    },
    sure() {
     this.$emit('close')
   },
  },
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.image .delete {
  position: relative;
  display: none;
}

.image:hover .delete {
  display: block;
}
</style>
